package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TimeHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        PrintWriter writer = new PrintWriter(response);

        try {
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            // 创建完整的HTML页面内容
            String htmlContent = "<!DOCTYPE html>\n" +
                    "<html lang=\"zh-CN\">\n" +
                    "<head>\n" +
                    "    <meta charset=\"UTF-8\">\n" +
                    "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                    "    <title>服务器时间 - MiniWebSvr</title>\n" +
                    "    <style>\n" +
                    "        body {\n" +
                    "            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n" +
                    "            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n" +
                    "            margin: 0;\n" +
                    "            padding: 0;\n" +
                    "            display: flex;\n" +
                    "            justify-content: center;\n" +
                    "            align-items: center;\n" +
                    "            min-height: 100vh;\n" +
                    "            color: #333;\n" +
                    "        }\n" +
                    "        .container {\n" +
                    "            background: white;\n" +
                    "            border-radius: 15px;\n" +
                    "            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);\n" +
                    "            padding: 40px;\n" +
                    "            text-align: center;\n" +
                    "            max-width: 500px;\n" +
                    "            width: 90%;\n" +
                    "        }\n" +
                    "        h1 {\n" +
                    "            color: #4a5568;\n" +
                    "            margin-bottom: 10px;\n" +
                    "            font-size: 24px;\n" +
                    "        }\n" +
                    "        .time-display {\n" +
                    "            font-size: 32px;\n" +
                    "            font-weight: bold;\n" +
                    "            color: #2d3748;\n" +
                    "            margin: 20px 0;\n" +
                    "            padding: 15px;\n" +
                    "            background: #f7fafc;\n" +
                    "            border-radius: 10px;\n" +
                    "            border: 2px solid #e2e8f0;\n" +
                    "        }\n" +
                    "        .info {\n" +
                    "            margin-top: 25px;\n" +
                    "            padding-top: 20px;\n" +
                    "            border-top: 1px solid #e2e8f0;\n" +
                    "            color: #718096;\n" +
                    "            font-size: 14px;\n" +
                    "        }\n" +
                    "        .student-info {\n" +
                    "            background: #edf2f7;\n" +
                    "            padding: 10px;\n" +
                    "            border-radius: 5px;\n" +
                    "            margin-top: 15px;\n" +
                    "        }\n" +
                    "    </style>\n" +
                    "</head>\n" +
                    "<body>\n" +
                    "    <div class=\"container\">\n" +
                    "        <h1>🕒 MiniWebSvr 服务器时间</h1>\n" +
                    "        <div class=\"time-display\" id=\"currentTime\">" + currentTime + "</div>\n" +
                    "        <p>这是服务器当前系统时间，每次刷新页面都会更新。</p>\n" +
                    "        \n" +
                    "        <div class=\"info\">\n" +
                    "            <p><strong>请求信息:</strong></p>\n" +
                    "            <p>请求方法: " + request.getMethod() + "</p>\n" +
                    "            <p>请求路径: " + request.getUrl() + "</p>\n" +
                    "            \n" +
                    "            <div class=\"student-info\">\n" +
                    "                <p><strong>开发者信息</strong></p>\n" +
                    "                <p>学号: 222024321072047</p>\n" +
                    "                <p>姓名: 李明燊</p>\n" +
                    "            </div>\n" +
                    "        </div>\n" +
                    "    </div>\n" +
                    "    \n" +
                    "    <script>\n" +
                    "        // 客户端时间同步显示（可选功能）\n" +
                    "        function updateClientTime() {\n" +
                    "            const now = new Date();\n" +
                    "            const options = { \n" +
                    "                year: 'numeric', \n" +
                    "                month: '2-digit', \n" +
                    "                day: '2-digit',\n" +
                    "                hour: '2-digit',\n" +
                    "                minute: '2-digit',\n" +
                    "                second: '2-digit',\n" +
                    "                hour12: false\n" +
                    "            };\n" +
                    "            document.getElementById('currentTime').innerHTML = \n" +
                    "                now.toLocaleDateString('zh-CN', options).replace(/\\//g, '-');\n" +
                    "        }\n" +
                    "        \n" +
                    "        // 每秒更新一次客户端时间\n" +
                    "        setInterval(updateClientTime, 1000);\n" +
                    "        updateClientTime(); // 立即执行一次\n" +
                    "    </script>\n" +
                    "</body>\n" +
                    "</html>";

            // TODO: [222024321072047/李明燊] 构造完整的 HTTP 响应头和响应体
            writer.println("HTTP/1.1 200 OK");
            writer.println("Content-Type: text/html; charset=UTF-8");
            writer.println("Content-Length: " + htmlContent.getBytes("UTF-8").length);
            writer.println("Connection: close");
            writer.println("Server: MiniWebSvr/1.0");
            writer.println("Cache-Control: no-cache, no-store, must-revalidate");
            writer.println("Pragma: no-cache");
            writer.println("Expires: 0");
            writer.println(); // 空行分隔头部和主体

            writer.print(htmlContent);
            writer.flush();

            System.out.println("TimeHandler: 成功返回时间页面 - " + currentTime);

        } catch (Exception e) {
            System.err.println("TimeHandler处理异常: " + e.getMessage());

            // 发生异常时返回错误响应
            try {
                String errorResponse = "HTTP/1.1 500 Internal Server Error\r\n" +
                        "Content-Type: text/plain; charset=UTF-8\r\n" +
                        "Connection: close\r\n" +
                        "\r\n" +
                        "服务器在处理时间请求时发生错误";
                response.write(errorResponse.getBytes("UTF-8"));
            } catch (IOException ioException) {
                System.err.println("发送错误响应失败: " + ioException.getMessage());
            }
        }
    }
}
